package cn.edu.gzhmt.user.web.servlet;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.gzhmt.cart.domain.Cart;
import cn.edu.gzhmt.user.domain.User;
import cn.edu.gzhmt.user.service.IUserService;
import cn.edu.gzhmt.user.service.UserException;
import cn.edu.gzhmt.user.service.impl.UserServiceImpl;
import cn.edu.gzhmt.utils.commons.CommonUtils;
import cn.edu.gzhmt.utils.mail.Mail;
import cn.edu.gzhmt.utils.mail.MailUtils;
import cn.edu.gzhmt.utils.web.servlet.BaseServlet;

public class UserServlet extends BaseServlet {
	private IUserService userService = new UserServiceImpl();

	/**
	 * 用户注册
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String register(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		/*
		 * 1、封装表单数据到form对象中
		 * 2、补全：uid、state（激活码）
		 * 		输入非空校验：在js进行验证
		 * 3、调用service方法完成注册
		 * 		失败：保存 异常信息、form对象 到request域，转发到regist.jsp
		 * 4、发邮件：让用户点击连接进行激活
		 * 5、保存成功信息，转发到/jsps/users/login.jsp
		 * */
		User form = CommonUtils.toBean(request.getParameterMap(), User.class);
		form.setUid(CommonUtils.uuid()); // 补全uid
		form.setState(CommonUtils.uuid() + CommonUtils.uuid()); // 补全state（激活码）
		form.setIsstate(false); // 补全Isstate（未激活）

		// 3、调用service方法完成注册
		Map<String, String> messages = new HashMap<String, String>();
		try {
			userService.regist(form);
		} catch (UserException e) {
			String message = e.getMessage();
			if (message.contains("用户名")) {
				messages.put("username", message);
			} else if (message.contains("邮箱")) {
				messages.put("email", message);
			} else {
				request.setAttribute("msg", message);
			}
			request.setAttribute("messages", messages);
			request.setAttribute("form", form);
			return "f:/jsps/users/register.jsp";

		}

		// 5、发邮件：让用户点击连接进行激活
		// 准备配置文件：properties文件
		// 获取配置文件的内容
		Properties props = new Properties();
		props.load(this.getClass().getClassLoader()
				.getResourceAsStream("email_template.properties"));
		String host = props.getProperty("host"); // 获取服务器的主机
		String uname = props.getProperty("uname"); // 获取用户名
		String pwd = props.getProperty("pwd"); // 获取密码
		String from = props.getProperty("from"); // 获取发件人
		String to = form.getEmail(); // 获取收件人
		String subject = props.getProperty("subject"); // 获取主题
		String content = props.getProperty("content"); // 获取邮件的内容
		content = MessageFormat.format(content, form.getCode()); // 替换{0}

		Session session = MailUtils.createSession(host, uname, pwd); // 得到Session
		Mail mail = new Mail(from, to, subject, content);
		try {
			// 发送邮件
			MailUtils.send(session, mail);
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}

		request.setAttribute("msg", "恭喜 " + form.getUsername()
				+ " 注册成功，请到邮箱点击链接进行激活。");

		return "f:/jsps/users/login.jsp";
	}

	/**
	 * 用户激活
	 * <a href="http://localhost:8080/shopping/UserServlet?method=active&state={0}">点击这里激活</a>
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String active(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// 获取激活码
		String stateCode = request.getParameter("state");

		// 进行用户激活
		try {
			userService.active(stateCode);
			request.setAttribute("msg", "用户激活成功，您可以登录了。");
		} catch (UserException e) {
			request.setAttribute("msg", e.getMessage());
		}

		return "f:/jsps/users/login.jsp";
	}

	/**
	 * 用户登录
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 封装表单数据
		User form = CommonUtils.toBean(request.getParameterMap(), User.class);

		// 进行登录
		try {
			User user = userService.login(form);

			// 用户登录成功，保存到Session域中
			request.getSession().setAttribute("user", user);

			// 分配购物车：保存在Session域中
			request.getSession().setAttribute("session_cart", new Cart());

		} catch (UserException e) {
			request.setAttribute("msg", e.getMessage());
			return "f:/jsps/users/login.jsp";
		}

		return "f:/index.jsp";
	}

	/**
	 * 用户退出
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String quit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 退出：销毁session
		request.getSession().invalidate();

		return "r:/index.jsp";
	}

	/**
	 * 进行用户信息的修改
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String editData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String uid = request.getParameter("uid");
		String columnName = request.getParameter("columnName");
		String value = request.getParameter("value");

		// 进行修改用户信息
		User user = null;
		Map<String, String> messages = new HashMap<String, String>();
		try {

			user = userService.editData(uid, columnName, value);
			// 更新Session中的用户信息
			request.getSession().setAttribute("user", user);

		} catch (UserException e) {
			messages.put(columnName, e.getMessage());
			request.setAttribute("messages", messages);

		}

		// response.getWriter().print("修改成功");

		// 输出修改后的结果，ajax会自动获取到结果
		return "f:/jsps/users/myInfo.jsp";
	}
}
